package com.xsj.controller;

import com.xsj.dto.ResponseDto;
import com.xsj.pojo.User;
import com.xsj.service.CartService;
import com.xsj.vo.Cart;
import com.xsj.vo.CartSyncRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @BelongsProject: wisdom-restaurant-manage
 * @BelongsPackage: com.xsj.controller
 * @Author: tutu
 * @CreateTime: 2025-06-17 09:47
 * @Description: 用户购物车管理
 * @Version: 1.0
 */

@CrossOrigin
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;


    @PostMapping("/addGood")
    public ResponseDto addGood(@RequestBody Cart cart) {
        if(cartService.addCart(cart)==1){
            return ResponseDto.success("添加成功");
        }else {
            return ResponseDto.err(202020, "添加失败");
        }
    }

    @GetMapping("/getGood")
    public ResponseDto getGood(@RequestParam("userId") int userId, @RequestParam("merchantId") int merchantId) {
        return ResponseDto.success(cartService.getCartFromRedis(userId, merchantId));
    }

    @PostMapping("/addGoodToMySQL")
    public ResponseDto addGoodToMySQL(@RequestBody CartSyncRequest request) {
        int userId = request.getUserId();
        int merchantId = request.getMerchantId();
        int i = cartService.addCartToMySQL(userId, merchantId);
        return ResponseDto.success(i);
    }


    @GetMapping("/getGoodFromMySQL")
    public ResponseDto getGoodFromMySQL(@RequestParam("userId") int userId, @RequestParam("merchantId") int merchantId) {
        Map<String, Cart> merchant = cartService.getCartForMerchant(userId, merchantId);
        return ResponseDto.success(merchant);

    }


    @GetMapping("/findByUserId")
    public ResponseDto findByUserId(@RequestParam("userId") int userId){
        return ResponseDto.success(cartService.findByUserId(userId));
    }

    @GetMapping("/delete")
    public ResponseDto delete(@RequestParam("userId") int userId,@RequestParam("merchantId") int merchantId,@RequestParam("goodId") int goodId){
        return ResponseDto.success(cartService.deleteCartFromRedis(userId,merchantId,goodId));
    }

    @GetMapping("/deleteToMySQL")
    public ResponseDto deleteToMySQL(@RequestParam("userId") int userId,@RequestParam("merchantId") int merchantId,@RequestParam("goodId") int goodId){
        return ResponseDto.success(cartService.deleteToMySQL(userId,merchantId,goodId));
    }

}
